<template>
  <!-- 应收管理列表页 -->
  <div>
    <div class="shareContainer" ref="shareContainer" v-show="checkType === ''">
      <!-- <el-tabs
        class="tab"
        type="border-card"
        v-model="activeName"
        @tab-click="Tabswitchover()"
      >
        <el-tab-pane label="待回款" name="0"> </el-tab-pane>
        <el-tab-pane label="已核销" name="1"> </el-tab-pane>
      </el-tabs> -->
      <div class="content-wrapper">
        <div class="actions" style="padding-bottom: 10px">
          <div class="left">
            <el-button
              @click="exportDerive()"
              plain
              type="primary"
              data-tracker="P49-4"
              v-permission="'finance_customer_delete'"
              >导出</el-button
            >
          </div>
          <div class="right" style="display: flex">
            <el-button
              type="primary"
              size="mini"
              @click="resultClickFn"
              style="margin: 0px 10px 0px 0px"
              >重置
            </el-button>
            <SettinUp
              :settype="headerId"
              :objSettinUpdata="objSettinUp"
              :key="activeName"
            ></SettinUp>
          </div>
        </div>
        <div class="table" v-if="header_data_list.length > 0" :key="activeName">
          <TableHeader
            ref="TableHeaderList"
            :header_data_list="header_data_list"
            :HeaderData="HeaderData"
            :propMap="propMap"
            :redact="''"
            :particulars="''"
            :objheader="objheader"
            :operation_type="3"
          >
            <template #operation="{ scope }">
              <!-- 接收内容：{{ scope }} -->
              <el-button
                size="small"
                type="text"
                v-show="activeName === '0'"
                @click="handleClickEdit(scope.row, 'edit')"
                data-tracker="P52-3"
                v-permission="'finance_receivable_update'"
                >编辑</el-button
              >
              <el-button
                size="small"
                type="text"
                data-tracker="P52-4"
                v-show="activeName === '1'"
                @click="handleClickEdit(scope.row, 'info')"
                >查看回款详情</el-button
              >
              <el-button
                size="small"
                type="text"
                data-tracker="P52-5"
                @click="receiptInfo(scope.row, 'info')"
                >查看申请详情</el-button
              >
            </template>
          </TableHeader>
        </div>
        <div class="actions" style="padding-top: 10px; width: 100%">
          <div class="left"></div>
          <div class="right">
            <el-pagination
              small
              background
              :current-page="paginations.pageIndex"
              :page-sizes="paginations.pageSizes"
              :page-size="paginations.pageSize"
              :layout="paginations.layout"
              :total="paginations.total"
              @size-change="handleSizeChange2"
              @current-change="handleCurrentChange2"
            />
          </div>
        </div>
        <el-dialog
          width="925px"
          title="回款详情"
          :visible.sync="showReturnInfo"
          :close-on-click-modal="false"
        >
          <el-form ref="form" :model="returnInfoData" :inline="true">
            <el-form-item label="申请单号" size="mini" style="width: 330px">
              <el-input
                disabled
                v-model="returnInfoData.source_no"
                style="width: 200px"
              ></el-input>
            </el-form-item>
            <el-form-item label="客户名称" size="mini" style="width: 330px">
              <el-input
                disabled
                v-model="returnInfoData.customer_id_name"
                style="width: 200px"
              ></el-input>
            </el-form-item>
            <el-form-item label="应收金额" size="mini" style="width: 330px">
              <el-input
                disabled
                v-model="returnInfoData.receivable_money"
                style="width: 200px"
              ></el-input>
            </el-form-item>
            <el-form-item label="实收金额" size="mini" style="width: 330px">
              <el-input
                disabled
                v-model="returnInfoData.received_money"
                style="width: 200px"
              ></el-input>
            </el-form-item>
          </el-form>
          <el-table
            ref="singleTable"
            :data="returnInfoData.receive_records"
            highlight-current-row
            style="width: 100%; margin-top: 10px"
            border
          >
            <el-table-column property="money" label="金额" width="130" key="11">
              <template slot="header">
                <span style="color: red">*</span>
                <span>金额</span>
              </template>
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.money"
                  :disabled="operateType === 'info'"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              property="receive_time"
              label="回款时间"
              width="200"
            >
              <template slot="header">
                <span style="color: red">*</span>
                <span>回款时间</span>
              </template>
              <template slot-scope="scope">
                <el-date-picker
                  :disabled="operateType === 'info'"
                  v-model="scope.row.receive_time"
                  type="datetime"
                  align="right"
                  unlink-panels
                  :picker-options="pickerOptions"
                  value-format="timestamp"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column
              property="receive_company"
              label="回款公司名称"
              width="180"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.receive_company"
                  :disabled="operateType === 'info'"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              property="type"
              label="操作人"
              width="150"
              key="12"
            >
              <template slot="header">
                <span style="color: red">*</span>
                <span>操作人</span>
              </template>
              <template slot-scope="scope">
                <el-select
                  filterable
                  :disabled="operateType === 'info'"
                  v-model="scope.row.creator_id"
                >
                  <el-option
                    v-for="(creator, index) in creatorList"
                    :key="creator.id + index"
                    :label="creator.nickname"
                    :value="creator.id"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              property="remark"
              label="备注"
              width="130"
              key="13"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.remark"
                  :disabled="operateType === 'info'"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              width="100"
              fixed="right"
              v-if="operateType !== 'info'"
            >
              <template slot-scope="scope">
                <i
                  @click="addOneLine"
                  class="el-icon-circle-plus-outline"
                  style="font-size: 26px"
                ></i>
                <i
                  @click="deleteOneLine(scope.$index)"
                  class="el-icon-remove-outline"
                  style="font-size: 26px; margin-left: 10px"
                ></i>
              </template>
            </el-table-column>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button @click="showReturnInfo = false">取 消</el-button>
            <!-- <el-button v-show="operateType !== 'info'" type="primary" @click="returnSubmit">保 存</el-button> -->
            <el-button
              v-if="activeName === '0'"
              type="primary"
              @click="returnSubmit('核销')"
              >保存</el-button
            >
          </div>
        </el-dialog>
        <div></div>
      </div>
    </div>
    <div v-show="checkType === 'edit' || checkType === 'info'">
      <customerCheckDetail></customerCheckDetail>
    </div>
    <div>
      <receiptDialog
        ref="receiptDialog"
        :invoice_id="invoice_id"
      ></receiptDialog>
    </div>
  </div>
</template>

<script>
import TableHeader from "@/page/orderform/components/TableHeader/tableheader.vue";
import SettinUp from "@/page/orderform/components/settingUp/settingUp.vue";
import { timestamp10 } from "@/utils/mUtils";
import pagination from "@/components/pagination";
import receiptDialog from "../receiptManage/receiptDialog.vue";
import { reqHandlersList } from "@/api/waybill";
import customerCheckDetail from "../customerlist/customerCheckDetail.vue";
import {
  reqReceivableList, //待回款，已核销列表
  reqReceivableInfo, //应收详情
  reqReceivableEdit, //应收编辑
  reqReceivableVerification, //应收核销或取消核销
  finance_receivable_list_export, //应收回款导出
} from "@/api/finance";
export default {
  name: "receivableManage",
  data() {
    return {
      showReturnInfo: false, //回款详情的弹出框
      invoice_id: "", //发票的id
      activeName: "0", //tabs切换
      customerList: [], //客户名称
      bigAreaList: [], //区域的列表
      salesList: [], //销售列表
      creatorList: [], //操作人
      checkSearchData: {
        // branch_id: "", //区域
        source_no: "", //单号
        customer_id: "", //客户名称
        user_id: "", //销售
        last_editor_id: "", //操作人
      }, //对账单维度查询条件
      returnInfoData: {
        //回款详情
        id: "",
        account_no: "",
        customer_name: "",
        accounts_receivable: "",
        paid_in_amount: "",
        receive_records: [], //回款详情的表格数据
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      pageNum: 1, //目前在第几页
      totalListNum: 10, //列表总数
      pageSize: 20, //一页多少条
      tableData: [], //主列表页
      selectedOrders: [], //选中的列表单子的id
      selectedDetails: [], //选中的列表单子的详细信息
      operateType: "",
      maxheight: 400,
      sumReceivedFee: "",
      pageSize2: 20,
      pageNum2: 1,
      searchParams: {},
      header_data_list: [],
      propMap: {},
      obj_list: {},
      HeaderData: [],
      waybillIdNums: [],
      operation_type: 0,
      dynParams: {},
      paginations: {
        pageIndex: 1, // 当前位于哪页
        pageSize: 20, // 1页显示多少条
        pageSizes: [10, 20, 50, 100], //每页显示多少条
        total: 200,
        layout: "total, sizes, prev, pager, next, jumper", // 翻页属性
      },
    };
  },
  components: {
    pagination,
    receiptDialog,
    customerCheckDetail,
    TableHeader,
    SettinUp,
  },
  mounted() {
    this.$store.commit("CHANGE_CHECK_TYPE", "");
    this.displayOrders();
    this.getHandlersList();
    if (this.$store.getters.customerList.length === 0) {
      this.$store.dispatch("getCustomerList");
    }
    if (this.$store.getters.websiteList.length === 0) {
      this.$store.dispatch("getWebsiteList");
    }
    if (this.$store.getters.adminList.length === 0) {
      this.$store.dispatch("getAdminList");
    }
  },
  computed: {
    checkType() {
      return this.$store.getters.checkType;
    },
    headerId() {
      return "51";
    },
  },
  watch: {
    $route: {
      handler(newV, oldV) {
        if (this.$route.query.type == 0) {
          this.activeName = "0";
          this.displayOrders();
        } else if (this.$route.query.type == 1) {
          this.activeName = "1";
          this.displayOrders();
        }
        // console.log(this.$route.query.type, "this.$route.query.type");
      },
      immediate: true,
      deep: true,
    },
    returnInfoData: {
      //加总实收金额
      deep: true,
      handler(newVal, oldVal) {
        let sum;
        sum = this.returnInfoData.receive_records.reduce(
          (pre, cur) => pre + cur.money * 1,
          0
        );
        this.returnInfoData.received_money = parseFloat(sum).toFixed(2);
      },
    },
  },
  methods: {
    resultClickFn() {
      this.paginations.pageIndex = 1;
      this.paginations.pageSize = 20;
      this.$refs.TableHeaderList.childMethod();
    },
    objSettinUp() {
      this.displayOrders();
    },
    //接收vuex的数据
    async getCustomerList() {
      this.customerList = this.$store.getters.customerList;
    },
    async getBigAreaList() {
      this.bigAreaList = this.$store.getters.websiteList;
    },
    async getSalesList() {
      this.salesList = this.$store.getters.adminList;
    },
    async getHandlersList() {
      let result = await reqHandlersList({ branch_id: "1" });
      this.creatorList = result.data;
      setTimeout(() => {
        this.checkSearchData.last_editor_id =
          JSON.parse(localStorage.getItem("user")).user_id * 1;
      }, 100);
    },

    async displayOrders(setHeader = true) {
      // console.log("数据的切换");
      const { checkSearchData, pageNum, pageSize } = this;
      let result;
      const params = {
        status: this.activeName, //  '状态，0待回款，1已核销
        page: this.paginations.pageIndex,
        page_size: this.paginations.pageSize,
        ...this.searchParams,
        header_id: this.headerId + "",
        // customer_id: checkSearchData.customer_id + "",
        // source_no: checkSearchData.source_no + "",
        // customer_id: checkSearchData.customer_id + "",
        // last_editor_id: checkSearchData.last_editor_id + "",
        // user_id: checkSearchData.user_id + "", // 所属销售id
      };
      this.dynParams = params;
      result = await reqReceivableList(params);
      if (result.code === 10000) {
        // // console.log(result,"resultresultresult")
        this.tableData = result.data.data || [];
        this.paginations.total = result.data.pagination.total;
        this.tableData.unshift({});
        this.header_data_list = this.tableData;
        if (setHeader) {
          this.HeaderData = result.data.item_list;
          this.Fntransformation(this.HeaderData);
        }
      }
    },
    objheader(obj) {
      this.paginations.pageIndex = 1;
      this.searchParams = obj;
      this.displayOrders(false);
    },
    Fntransformation(obj) {
      const result = {};
      for (const prop in obj) {
        if (obj.hasOwnProperty(prop)) {
          if (obj[prop].send_name !== "") {
            result[obj[prop].name] = obj[prop].show_name;
          } else {
            result[obj[prop].name] = obj[prop].name;
          }
        }
      }
      this.propMap = result;
    },
    resettingData() {
      // console.log("fjsalksf==============================");
      Object.assign(
        this.$data.checkSearchData,
        this.$options.data().checkSearchData
      );
      this.displayOrders();
    },
    async handleClickEdit(row, operate) {
      this.operateType = operate;
      let result = await reqReceivableInfo({
        id: row.id,
      });
      // console.log(result, "result");
      if (result.code === 10000) {
        this.returnInfoData = result.data;
        // console.log(
        //   this.returnInfoData.receive_records,
        //   "this.returnInfoData.receive_records"
        // );
        if (
          this.returnInfoData.receive_records.length == 0 &&
          this.operateType === "edit"
        ) {
          this.returnInfoData.receive_records.push({
            // received_amount: "", // 金额
            // payment_company: "",
            // last_editor_id:
            //   JSON.parse(localStorage.getItem("user")).user_id * 1,
            // received_time: new Date().getTime(), // 收款时间
            money: "", // 回款金额
            receive_time: new Date().getTime(), // 回款时间
            receive_company: "", // 回款公司
            creator_id: JSON.parse(localStorage.getItem("user")).user_id * 1, // 操作人id
            remark: "", // 备注
          });
        } else {
          this.returnInfoData.receive_records.forEach((item) => {
            // item.last_editor_id = item.last_editor_id * 1;
            // item.received_time = item.received_time * 1000;
            item.creator_id = item.creator_id * 1;
            item.receive_time = item.receive_time * 1000;
          });
        }
      }
      this.showReturnInfo = true;
    },
    async cancelVerification(row) {
      //取消核销
      let result = await reqReceivableVerification({
        id: row.id,
        status: "0", //核销状态： 1-已核销,0-待收款
      });
      if (result.code === 10000) {
        this.$message({
          type: "success",
          message: result.message,
        });
        this.displayOrders();
      }
    },
    async returnSubmit(val) {
      //提交编辑汇款

      if (
        val === "核销" &&
        this.returnInfoData.receivable_money * 1 <
          this.returnInfoData.received_money * 1
      ) {
        this.$message({
          type: "error",
          message: "打款金额不能超过实际报销金额",
        });
        return;
      }
      let receType = 0;
      this.returnInfoData.receive_records.forEach((item) => {
        if (item.money != 0) {
          // item.received_amount = item.received_amount * 1;
          // item.last_editor_id = item.last_editor_id + "";
          // item.received_time = timestamp10(item.received_time) * 1;
          item.money = item.money + "";
          item.creator_id = item.creator_id + "";
          item.receive_time = timestamp10(item.receive_time) + "";
          receType = 1;
        } else {
          receType = 0;
        }
      });
      if (receType == 1) {
        let result = await reqReceivableEdit({
          id: this.returnInfoData.id,
          receive_records: this.returnInfoData.receive_records,
        });
        if (result.code === 10000) {
          this.$message({
            type: "success",
            message: result.message,
          });
          this.showReturnInfo = false;
          this.displayOrders();
        }
      } else {
        this.$message({
          message: "请输入金额",
          type: "warning",
        });
      }
    },
    // async verificationSubmit() {
    //   //核销
    //   let result = await reqReceivableVerification({
    //     id: this.returnInfoData.id,
    //     status: "1", //核销状态： 1-已核销,0-待收款
    //   });
    //   if (result.code === 10000) {
    //     this.$message({
    //       type: "success",
    //       message: result.message,
    //     });
    //     this.showReturnInfo = false;
    //     this.displayOrders();
    //   }
    // },
    receiptInfo(row) {
      // console.log(row, "row");
      // this.invoice_id = row.invoice_id;
      this.$store.commit("CHANGE_OPERATE_TYPE", "info");
      // this.$refs.receiptDialog.dialogVisible = true;
      this.$router.push({
        name: "receiptManageadd",
        query: {
          id: row.source_id,
          Type: 2,
          TageType: 0,
        },
      });
    },
    handleSelectionChange(checked) {
      // console.log(checked);
      this.selectedOrders = checked.map((item) =>
        item.id ? item.id : item.invoice_detail.id
      );
      this.selectedDetails = checked;
    },
    handleSizeChange2(val) {
      this.paginations.pageSize = val;
      this.displayOrders();
    },
    handleCurrentChange2(val) {
      this.paginations.pageIndex = val;
      this.displayOrders();
    },
    clickToDetail(id) {
      this.$store.commit("GET_CHECK_DETAIL_ID", id + "");
      this.$store.commit("CHANGE_CHECK_TYPE", "info");
    },
    addOneLine() {
      this.returnInfoData.receive_records.push({
        // received_amount: "", // 金额
        // payment_company: "",
        // last_editor_id: JSON.parse(localStorage.getItem("user")).user_id * 1,
        // received_time: new Date().getTime(), // 收款时间
        money: "", // 回款金额
        receive_time: new Date().getTime(), // 回款时间
        receive_company: "", // 回款公司
        creator_id: JSON.parse(localStorage.getItem("user")).user_id * 1, // 操作人id
        remark: "", // 备注
      });
    },
    deleteOneLine(index) {
      if (this.returnInfoData.receive_records.length > 1) {
        this.returnInfoData.receive_records.splice(index, 1);
      }
    },
    Tabswitchover() {
      this.paginations.pageSize = 20; //一页多少条
      this.paginations.pageIndex = 1; //第多少页
      Object.assign(
        this.$data.checkSearchData,
        this.$options.data().checkSearchData
      );
      this.displayOrders();
    },
    exportDerive() {
      var params = {
        status: this.activeName, //  '状态，0待回款，1已核销
        ...this.searchParams,
        header_id: this.headerId + "",
      };
      finance_receivable_list_export(params).then((res) => {
        this.reqUrl = "https://" + res.data.url;
        window.open(this.reqUrl);
      });
    },
  },
};
</script>

<style lang="less" scoped>
// /deep/ .el-tabs__nav-wrap {
//   left: -178px;
// }
.shareContainer {
  padding: 10px 15px;
  background-color: #fff;

  .el-form-item--mini.el-form-item {
    margin-bottom: 10px;
  }

  .operation {
    height: 40px;

    .el-button {
      margin-left: 0px;
      margin-right: 10px;
    }

    ::v-deep .el-pagination {
      float: right;
      margin: 0px 0px 0px 20px;

      .el-input--mini .el-input__inner {
        height: 24px;
      }
    }
  }

  /deep/ .el-tabs--border-card > .el-tabs__content {
    padding: 0px;
  }

  .content-wrapper {
    // padding: 15px;
  }

  .tab.el-tabs--border-card {
    border: none;
    box-shadow: none;

    .el-tabs__content {
      padding: 0;
      height: 40px;
    }
  }
}

.actions {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  width: 100%;
  background-color: #fff;

  .el-button + .el-dropdown,
  .el-dropdown + .el-button {
    margin-left: 10px;
  }
}
</style>